package cn.han.tickets;

public class TestRunnableV1 {
    public static void main(String[] args) {
        TicketRunnablev1 t1 = new TicketRunnablev1();
        Thread thread = new Thread(t1,"灰太狼");
        Thread thread2 = new Thread(t1,"红太狼");
        Thread thread1 = new Thread(t1,"焦太狼");
        Thread thread3 = new Thread(t1,"黄太狼");

        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

class TicketRunnablev1 implements Runnable {
    //由于自定义类对象值创建了一次，所以票数被所有线程对象Thread类的对象共享
    int tickets = 100;

    @Override
    public void run() {
        while (true) {
            synchronized (TicketRunnablev1.class) {
                if (tickets > 0) {

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + tickets--);
                    if (tickets <= 0) break;
                }
            }
        }
    }
}
